package cn.wokoba.service.activity.service.discount;

import cn.wokoba.service.activity.adapter.repository.IActivityRepository;
import cn.wokoba.service.activity.model.valobj.DiscountTypeEnum;
import cn.wokoba.service.activity.model.valobj.GroupBuyActivityDiscountVO;
import jakarta.annotation.Resource;

import java.math.BigDecimal;

public abstract class AbstractDiscountCalculateService implements IDiscountCalculateService {
    @Resource
    protected IActivityRepository repository;
    @Override
    public BigDecimal calculate(String userId, BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount) {
        // 1. 人群标签过滤
        if (DiscountTypeEnum.TAG.equals(groupBuyDiscount.getDiscountType())) {
            boolean isCrowdRange = filterTagId(userId, groupBuyDiscount.getTagId());
            if (!isCrowdRange) return originalPrice;
        }
        // 2. 折扣优惠计算
        BigDecimal deductionPrice = doCalculate(originalPrice, groupBuyDiscount);

        //折扣后金额小于0也需要支付0.01
        return deductionPrice.compareTo(BigDecimal.ZERO) <= 0 ? new BigDecimal("0.01") : deductionPrice;
    }

    // 人群过滤 - 限定人群优惠
    private boolean filterTagId(String userId, String tagId) {
        return repository.isTagCrowdRange(tagId, userId);

    }

    protected abstract BigDecimal doCalculate(BigDecimal originalPrice, GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount);
}
